package com.version1_1.service.implement;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.util.page.GetPageModel;
import com.util.property.Properties;
import com.version1_1.dao.PageDao;
import com.version1_1.model.MainPageModel;
import com.version1_1.service.PageService;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class PageServiceImpl implements PageService {

    /*创建Log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(PageServiceImpl.class);

    @Autowired
    private PageDao pageDao;


    /**
     * @param commentString
     * @return
     * @name: setPageComment
     * @description: 新增一条评论或回复或改变一条评论的点赞数
     */
    @Override
    public String setPageComPraise(String commentString) {
        Map<String, Object> setPageComPraiseMap = new HashMap<>();
        setPageComPraiseMap.put("commentOK", pageDao.setPageComPraise(commentString));

        /**
         * {"commentOK":true/false}
         */
        return JSON.toJSONString(setPageComPraiseMap);
    }

    /**
     * @param commentString
     * @return
     * @Description: 新增一条评论或回复
     * @Title: setPageComment
     */
    @Override
    public String setPageComment(String commentString) {
        int commentId = pageDao.setPageComment(commentString);
        boolean result = (commentId == 0) ? false : true;
        Map<String, Object> setPageCommentMap = new HashMap<>();
        setPageCommentMap.put("commentOK", result);
        setPageCommentMap.put("commentId", commentId);

        /**
         * {"commentOK":true/false,"commentId":}
         */
        return JSON.toJSONString(setPageCommentMap);
    }

    /**
     * @param pageId
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getCommentListString
     * @description: 获取文章评论列表数据
     */
    @Override
    public String getCommentListString(int userId, int pageId, int pageNumber, int pageSize) {
        List commentList = pageDao.getCommentList(pageId, pageNumber, pageSize);

        boolean isLast = false;
        Map<String, Object> getCommentListStringMap = new HashMap<>();

        if (commentList == null || commentList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < commentList.size(); i++) {
                Map commentMap = (Map) commentList.get(i);
                int commentId = (int) commentMap.get("commentId");
                String userName = (String) commentMap.get("userName");
                String userPhoto = (String) commentMap.get("userPhoto");
                String comContent = (String) commentMap.get("comContent");
                String date = (String) commentMap.get("date");

                //排除JSON字符串key的value为"null"的情况
                if (userName == null) {
                    commentMap.replace("userName", "");
                }

                if (userPhoto == null) {
                    commentMap.replace("userPhoto", "");
                } else {
                    commentMap.replace("userPhoto", userPhoto + Properties.ImageLowQuality);
                }

                if (comContent == null) {
                    commentMap.replace("comContent", "");
                }
                if (date == null) {
                    commentMap.replace("date", "");
                }

                if (userId != -1) {
                    commentMap.put("hasPraised", pageDao.checkPraised(commentId, userId));
                }
            }
        }


        getCommentListStringMap.put("isLast", isLast);
        getCommentListStringMap.put("commentList", commentList);
        return JSON.toJSONString(getCommentListStringMap);
    }

    /**
     * @param key
     * @return
     * @name: searchPage
     * @Description: 搜索文章标题
     */
    @Override
    public String searchPage(String key) {
        List<Map<String, Object>> searchList = pageDao.searchPage(key); // 搜索结果
        boolean hasResult = true; // 是否有搜索结果
        Map<String, Object> searchPageMap = new HashMap<>(); // 搜索结果Map

        if (searchList.isEmpty()) {
            LOGGER.info("根据关键词未搜索到文章,搜索关键字为: " + key);
            hasResult = false;
        } else {
            for (int i = 0; i < searchList.size(); i++) {
                Map<String, Object> temp = searchList.get(i);
                temp.replace("imageSrc", temp.get("imageSrc") + Properties.ImageLowQuality);
            }
        }

        searchPageMap.put("hasResult", hasResult);
        searchPageMap.put("searchResult", searchList);
        return JSON.toJSONString(searchPageMap);
    }

    /**
     * @param pageId
     * @return {"doReadResult":true/false}
     * @name: doRead
     * @description: 记录文章被用户阅读
     */
    @Override
    public String doRead(int pageId) {
        Map<String, Object> doReadMap = new HashMap<>();
        doReadMap.put("doReadResult", pageDao.doRead(pageId));
        return JSON.toJSONString(doReadMap);
    }

    /**
     * @param pageId
     * @return {"doTransmitResult":true/false}
     * @name: doTransmitCount
     * @Description: 记录文章被转发(分享)
     */
    @Override
    public String doTransmitCount(int pageId) {
        Map<String, Object> doTransmitCountMap = new HashMap<>();
        doTransmitCountMap.put("doTransmitResult", pageDao.doTransmitCount(pageId));
        return JSON.toJSONString(doTransmitCountMap);
    }

    /**
     * @param userId
     * @param pageId
     * @param commentType
     * @return
     * @Description: 评论文章水文/好文
     */
    @Override
    public boolean pageContentComment(int userId, int pageId, int commentType) {
        return pageDao.pageContentComment(userId, pageId, commentType);
    }

    /**
     * @param comInPageStr
     * @return
     * @Description: 在文章中对三级分类信息进行评论和提供信息源
     */
    @Override
    public boolean postComInPage(String comInPageStr) {
        JSONObject comInPageJsonObject = null;

        // 如果接收到的Json字符串格式有误
        try {
            comInPageJsonObject = JSONObject.fromObject(comInPageStr);
        } catch (Exception exception) {
            LOGGER.error("在文章中对三级分类信息进行评论和提供信息源出错,用户传递Json字符串格式错误,comInPageStr: " + comInPageStr);
            return false;
        }

        int userId = comInPageJsonObject.getInt("userId"); // 用户ID
        String wantedInfo = comInPageJsonObject.getString("wantedInfo"); // 用户想要的信息
        String infoSource = comInPageJsonObject.getString("infoSource"); // 信息源

        // 如果想要的信息为null
        if (wantedInfo == null) {
            wantedInfo = "";
        }
        // 如果信息源为null
        if (infoSource == null) {
            infoSource = "";
        }

        return pageDao.postComInPage(userId, wantedInfo, infoSource);
    }

    /**
     * @param commentId
     * @return
     * @Description: TODO(获取评论的回复列表)
     */
    @Override
    public String getCommentReply(int commentId) {
        List comReplyList = pageDao.getCommentReply(commentId);
        boolean hasComReply = true;
        Map<String, Object> getCommentReplyMap = new HashMap<>();

        if (comReplyList.isEmpty()) {
            hasComReply = false;
        } else {
            for (int i = 0; i < comReplyList.size(); i++) {
                Map<String, Object> comReplyMap = (Map<String, Object>) comReplyList.get(i);

                if (comReplyMap.get("replyerPhoto") == null) {
                    comReplyMap.replace("replyerPhoto", "");
                } else {
                    comReplyMap.replace("replyerPhoto", comReplyMap.get("replyerPhoto") + Properties.ImageLowQuality);
                }
            }
        }

        getCommentReplyMap.put("hasComReply", hasComReply);
        getCommentReplyMap.put("comReplyList", comReplyList);
        return JSON.toJSONString(getCommentReplyMap);
    }

    /**
     * @param pageId
     * @return html String
     * @name: getPageInfoString
     * @description: 根据pageId获取信息数据字符串
     */
    @Override
    @Cacheable(value = {"pageInfoCacheVersion1_1"})
    @CacheEvict(value = "pageInfoCacheVersion1_1", condition = "#cleanCache==true", allEntries = true)
    public String getPageInfo(int pageId, boolean cleanCache) {
        List pageContentList = pageDao.getPageInfo(pageId);

        if (pageContentList == null || pageContentList.isEmpty()) {
            return "";
        }

        Map resultMap = (Map) pageContentList.get(0);

        //得到标题和页面内容
        String firstTitle = (String) resultMap.get("firstTitle");
        String pageContent = (String) resultMap.get("pageContent");
        String pageFrom = (String) resultMap.get("pageFrom");
        String pageDate = resultMap.get("pageDate").toString();
        String imageSrc = (String) resultMap.get("imageSrc");
        long readNumber = (long) resultMap.get("readNumber");
        String sourceAddress = (String) resultMap.get("sourceAddress");

        if (sourceAddress == null) {
            sourceAddress = "";
        }

        String htmlString = "";

        String pageModelStr = GetPageModel.getPageModelStr(Properties.Page_ModelURL);
        htmlString = pageModelStr;
        htmlString = htmlString.replace("{kuibu_pageTitle}", firstTitle);
        htmlString = htmlString.replace("{kuibu_pageReadNumber}", String.valueOf(readNumber));
        htmlString = htmlString.replace("{kuibu_pageFrom}", pageFrom);
        htmlString = htmlString.replace("{kuibu_pageContent}", pageContent);
        htmlString = htmlString.replace("{kuibu_pageTitleImage}", imageSrc + Properties.ImageHighQuality);
        htmlString = htmlString.replace("{kuibu_pageDate}", pageDate);
        htmlString = htmlString.replace("{kuibu_sourceAddress}", sourceAddress);

        return htmlString;
    }

    /**
     * @param pageId
     * @return
     * @Title: getPageOtherInfo
     * @Description: 获取除正文之外其他信息
     */
    @Override
    public String getPageOtherInfo(int userId, int pageId) {
        Map<String, Object> pageOtherInfoMap = pageDao.getPageOtherInfo(userId, pageId);
        List<Map<String, Object>> recomArtcList = (List<Map<String, Object>>) pageOtherInfoMap.get("recomArtc"); //推荐文章数组
        List<Map<String, Object>> comFirPageList = (List<Map<String, Object>>) pageOtherInfoMap.get("comFirPage"); //第一页评论列表

        Map<String, Object> getPageOtherInfoMap = new HashMap<>();

        /**
         * 推荐文章标题图片URL处理
         */
        for (Map tempMap : recomArtcList) {
            tempMap.replace("imageSrc", (String) tempMap.get("imageSrc") + Properties.ImageHighQuality);
        }

        /**
         * 评论列表用户头像URL处理
         */
        for (Map tempMap : comFirPageList) {
            String userPhoto = (String) tempMap.get("userPhoto");
            tempMap.replace("userPhoto", userPhoto + Properties.ImageLowQuality);
        }

        getPageOtherInfoMap.put("recomArtc", recomArtcList);
        getPageOtherInfoMap.put("comFirPage", comFirPageList);
        getPageOtherInfoMap.put("praNum", (int) pageOtherInfoMap.get("praNum"));
        getPageOtherInfoMap.put("criNum", (int) pageOtherInfoMap.get("criNum"));
        getPageOtherInfoMap.put("userChoice", (int) pageOtherInfoMap.get("userChoice"));
        getPageOtherInfoMap.put("adPicUrl", (String) pageOtherInfoMap.get("adPicUrl"));
        getPageOtherInfoMap.put("adLink", (String) pageOtherInfoMap.get("adLink"));
        getPageOtherInfoMap.put("isSubscri", (boolean) pageOtherInfoMap.get("isSubscri"));
        getPageOtherInfoMap.put("comNum", (int) pageOtherInfoMap.get("comNum"));
        return JSON.toJSONString(getPageOtherInfoMap);
    }

    /**
     * @param mainFocusList
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getMainPageNoLogin
     * @description: 未登陆用户根据分页数得到主页面的预览信息
     * @description: 图片传递url
     */
    @Override
    public String getMainPageNoLogin(String mainFocusList, int pageNumber,
                                     int pageSize) {
        List pageListNoLoginList = pageDao.getPageListNoLogin(mainFocusList,
                pageNumber, pageSize);
        List titleList = null;
        boolean isLast = false;
        Map<String, Object> getMainPageNoLoginMap = new HashMap<>();

        //获取数据为空或者获取数据错误
        if (pageListNoLoginList == null || pageListNoLoginList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageListNoLoginList.size(); i++) {
                Map pageMap = (Map) pageListNoLoginList.get(i);
                pageMap.replace("imageString", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }
        }

        /**
         * 如果是第一页，有大图数据
         */
        if (pageNumber == 1) {
            titleList = pageDao.getTitleList(JSONObject.fromObject(mainFocusList).getInt("itemNumber"));
            for (int i = 0; i < titleList.size(); i++) {
                Map titleMap = (Map) titleList.get(i);
                titleMap.replace("imageSrc2", (String) titleMap.get("imageSrc2") + Properties.ImageQuality);
            }
        }

        getMainPageNoLoginMap.put("isLast", isLast);
        getMainPageNoLoginMap.put("result", pageListNoLoginList);
        getMainPageNoLoginMap.put("title", titleList);
        return JSON.toJSONString(getMainPageNoLoginMap);
    }

    /**
     * @param mainFocusList
     * @param pageNumber
     * @param pageSize
     * @param cacheTag      @return String    返回类型
     * @throws
     * @Title: getMainPageNoLogin
     * @Description: TODO(获取未登陆用户主页面预览信息，新接口)
     */
    @Override
    @Cacheable(value = {"noLoginMainPageVersion1_1"})
    @CacheEvict(value = "noLoginMainPageVersion1_1", condition = "#cacheTag==true", allEntries = true)
    public String getNewMainPageNoLogin(String mainFocusList, int pageNumber, int pageSize, boolean cacheTag) {
        List pageListNoLogin = pageDao.getPageListNoLogin(mainFocusList,
                pageNumber, pageSize);
        List titleList = null;
        boolean isLast = false;

        //得到firstType
        JSONObject jsonObject = JSONObject.fromObject(mainFocusList);
        int firstType = jsonObject.getInt("itemNumber");

        /**
         * 图片URL处理
         */
        if (pageListNoLogin == null || pageListNoLogin.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageListNoLogin.size(); i++) {
                Map pageMap = (Map) pageListNoLogin.get(i);
                pageMap.replace("imageString", (String) pageMap.get("imageString") + Properties.ImageQuality);
            }
        }

        /**
         * 如果是第一页，有大图数组，进行图片URL处理
         */
        if (pageNumber == 1) {
            titleList = pageDao.getTitleList(firstType);
            // 遍历list得到JSON String
            for (int i = 0; i < titleList.size(); i++) {
                Map titleMap = (Map) titleList.get(i);
                titleMap.replace("imageString", ((Map) titleList.get(i)).get("imageString") + Properties.ImageHighQuality);
            }
        }


        Map<String, Object> getNewMainPageNoLoginMap = new HashMap<>();
        getNewMainPageNoLoginMap.put("result", pageListNoLogin);
        getNewMainPageNoLoginMap.put("isLast", isLast);
        getNewMainPageNoLoginMap.put("title", titleList);
        return JSON.toJSONString(getNewMainPageNoLoginMap);
    }

    /**
     * @param userId
     * @param firstType
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getMainPage
     * @description: 获取登陆用户主页面预览信息数据，新接口
     * @description: 图片传递url
     */
    @Override
    @Cacheable(value = {"loginMainPageVersion1_1"})
    @CacheEvict(value = "loginMainPageVersion1_1", condition = "#cacheTag==true", allEntries = true)
    public String getNewMainPage(int userId, int firstType, int pageNumber,
                                 int pageSize, boolean cacheTag) {

        MainPageModel mainPageModel = pageDao.getNewMainPage(userId, firstType, pageNumber,
                pageSize);

        // 处理mainPageModel中图片的URL路径
        if (!mainPageModel.isLast()) {
            for (Map pageMap : mainPageModel.getPageList()) {
                pageMap.replace("imageString", (String) pageMap.get("imageString") + Properties.ImageQuality);
            }
        }

        if (mainPageModel.getTitleList() != null) {
            for (Map titleMap : mainPageModel.getTitleList()) {
                titleMap.replace("imageString", (String) titleMap.get("imageString") + Properties.ImageQuality);
            }
        }

        return mainPageModel.jsonSerialize();
    }

    /**
     * @param userId
     * @param firstType
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getMainPage
     * @description: 获取登陆用户主页面预览信息数据
     * @description: 图片传递url
     */
    @Override
    public String getMainPage(int userId, int firstType, int pageNumber,
                              int pageSize) {
        List pageList = pageDao.getPageList(userId, firstType, pageNumber,
                pageSize);
        boolean isLast = false;
        List titleList = null;
        Map<String, Object> getMainPageMap = new HashMap<>();

        if (pageList == null || pageList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageList.size(); i++) {
                Map pageMap = (Map) pageList.get(i);
                pageMap.replace("imageSrc", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }

            // 如果是第一页数据，则有滑图数据
            if (pageNumber == 1) {
                titleList = pageDao.getTitleList(firstType);

                if (titleList == null || titleList.isEmpty()) {
                    LOGGER.error("一级分类滑图数据为空,一级分类ID为：" + firstType);
                } else {
                    for (int i = 0; i < titleList.size(); i++) {
                        Map titleMap = (Map) titleList.get(i);
                        titleMap.replace("imageSrc2", (String) titleMap.get("imageSrc2") + Properties.ImageHighQuality);
                    }
                }
            }
        }

        getMainPageMap.put("isLast", isLast);
        getMainPageMap.put("result", pageList);
        getMainPageMap.put("title", titleList);
        return JSON.toJSONString(getMainPageMap);
    }


    /**
     * @param secondFocusListString
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getSecondPage
     * @description: 根据分页数得到二级分类界面的预览信息
     * @description: 图片传递url
     */
    @Override
    public String getSecondPage(String secondFocusListString, int pageNumber,
                                int pageSize) {
        List pageList = pageDao.getSecondPageList(secondFocusListString,
                pageNumber, pageSize);
        boolean isLast = false;
        Map<String, Object> getSecondPageMap = new HashMap<>();

        if (pageList == null || pageList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageList.size(); i++) {
                Map pageMap = (Map) pageList.get(i);
                pageMap.replace("imageSrc", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }
        }

        getSecondPageMap.put("isLast", isLast);
        getSecondPageMap.put("result", pageList);
        return JSON.toJSONString(getSecondPageMap);
    }

    /**
     * @param secondType
     * @param thirdTypeName
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getThirdPage
     * @description: 获取三级分类页面预览信息数据
     * @description: 图片传递url
     */
    @Override
    @Cacheable(value = {"thirdTypePageCacheVersion1_1"})
    public String getThirdPage(int secondType, String thirdTypeName,
                               int pageNumber, int pageSize) {
        List pageList = pageDao.getThirdPageList(secondType, thirdTypeName,
                pageNumber, pageSize);
        boolean isLast = false;
        Map<String, Object> getThirdPageMap = new HashMap<>();

        if (pageList == null || pageList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageList.size(); i++) {
                Map pageMap = (Map) pageList.get(i);
                pageMap.replace("imageString", (String) pageMap.get("imageString") + Properties.ImageQuality);
            }
        }

        getThirdPageMap.put("isLast", isLast);
        getThirdPageMap.put("result", pageList);
        return JSON.toJSONString(getThirdPageMap);
    }

}
